package com.oa.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oa.bean.ContrUser;
import com.oa.bean.Contract;
import com.oa.bean.Section;
import com.oa.bean.User;
import com.oa.service.impl.CMServiceImpl;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

@Controller
@RequestMapping("/showCon")
public class ContractManage {
	
	@Autowired
	private CMServiceImpl cMService;

	/**
	 * 查询所有的部门信息
	 * @return
	 */
	@RequestMapping("/findSec")
	@ResponseBody
	public Map<String, Object> findSec(){
		List<Section> sections=cMService.findSec();
		System.out.println(sections);
		Map<String, Object> map=new HashMap<>();
		map.put("sections", sections);
		return map;
	}
	
	/**
	 * 根据部门id查询员工信息
	 * @param seorid
	 * @return
	 */
	@RequestMapping("/findUser")
	@ResponseBody
	public Map<String, Object> findUser(int seorid){
		System.out.println(seorid);
		List<User> users=cMService.findUser(seorid);
		System.out.println(users);
		Map<String, Object> map=new HashMap<>();
		map.put("users", users);
		return map;
	}
	
	/**
	 * 添加合同信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/addCon")
	public String addCon(HttpServletRequest request){
		String con_emp=request.getParameter("user");
		String con_num=request.getParameter("number");
		String con_type=request.getParameter("type");
		String con_status=request.getParameter("ckey");
		String con_signdate=request.getParameter("signdate");
		String con_trydate=request.getParameter("testdate");
		int con_tryday=Integer.parseInt(request.getParameter("testday"));
		String con_tryend=request.getParameter("testenddate");
		int con_signnum=Integer.parseInt(request.getParameter("signnum"));
		String con_end=request.getParameter("signenddate");
		String con_enclo=request.getParameter("appendix");
		String con_remaks=request.getParameter("replyContent");
		System.out.println(con_signdate);
		
		
		Contract contract=new Contract();
		contract.setCon_emp(con_emp);
		contract.setCon_num(con_num);
		contract.setCon_type(con_type);
		contract.setCon_status(con_status);
		contract.setCon_signdate(con_signdate);
		contract.setCon_trydate(con_trydate);
		contract.setCon_tryday(con_tryday);
		contract.setCon_tryend(con_tryend);
		contract.setCon_signnum(con_signnum);
		contract.setCon_end(con_end);
		contract.setCon_enclo(con_enclo);
		contract.setCon_remaks(con_remaks);
		
		System.out.println(contract);
		int result=cMService.addCon(contract);
		
		return "../Template/showContract";
	}
	
	/**
	 * 页面展示合同信息
	 * @param currentPage
	 * @return
	 */
	@RequestMapping("/showContract")
	@ResponseBody
	public Map<String, Object> showContract(Integer currentPage,String emp,String type,String status,String date1,String date2,String date3,String date4){
		System.out.println(emp+" "+type+" "+status);
		Contract contract=new Contract();
		contract.setCon_emp(emp);
		contract.setCon_type(type);
		contract.setCon_status(status);
		contract.setCon_signdate(date1);
		contract.setCon_trydate(date2);
		contract.setCon_tryend(date3);
		contract.setCon_end(date4);
		System.out.println(contract);
		
		if(currentPage==0){
			currentPage=1;
		}
		System.out.println("currentPage="+currentPage);
		Page<PageInfo> pageInfo=PageHelper.startPage(currentPage, 5,"con_num desc");
		
		List<ContrUser> contrUsers=cMService.findCon(contract);
		System.out.println(contrUsers);
		Map<String, Object> map=new HashMap<>();
		map.put("contrUsers", contrUsers);
		map.put("pages", pageInfo.getPages());
		return map;
	}
	
	/**
	 * 判断合同是否存在
	 * @param uname
	 * @return
	 */
	@RequestMapping("/dec")
	@ResponseBody
	public Map<String, Object> dec(String uname){
		Contract contract=cMService.dec(uname);
		System.out.println(contract);
		Map<String, Object> map=new HashMap<>();
		map.put("contract", contract);
		return map;
	}
	
	/**
	 * 查看人事合同信息
	 * @param con_num
	 * @return
	 */
	@RequestMapping("/findCon")
	@ResponseBody
	public Map<String, Object> findCon(String con_num){
		Contract contract=cMService.findContr(con_num);
		System.out.println(contract);
		Map<String, Object> map=new HashMap<>();
		map.put("contract", contract);
		return map;
	}
	
	/**
	 * 根据id查找人事合同信息
	 * @param con_id
	 * @return
	 */
	@RequestMapping("/findCon1")
	public String findCon1(int con_id,Model model){
		System.out.println(con_id);
		ContrUser contrUser=cMService.findCon1(con_id);
		System.out.println(contrUser);
		model.addAttribute("contrUser", contrUser);
		return "../Template/updateCon";
	}
	
	/**
	 * 编辑人事合同信息
	 * @param con_id
	 * @return
	 */
	@RequestMapping("/updateCon")
	public String updateCon(HttpServletRequest request){
		int con_id=Integer.parseInt(request.getParameter("con_id"));
		System.out.println(con_id);
		String con_emp=request.getParameter("user");
		String con_num=request.getParameter("number");
		String con_type=request.getParameter("type");
		String con_status=request.getParameter("ckey");
		String con_signdate=request.getParameter("signdate");
		String con_trydate=request.getParameter("testdate");
		int con_tryday=Integer.parseInt(request.getParameter("testday"));
		String con_tryend=request.getParameter("testenddate");
		int con_signnum=Integer.parseInt(request.getParameter("signnum"));
		String con_end=request.getParameter("signenddate");
		String con_enclo=request.getParameter("appendix");
		System.out.println(con_enclo);
		String con_remaks=request.getParameter("replyContent");
		System.out.println(con_signdate);
		
		
		Contract contract=new Contract();
		contract.setCon_id(con_id);
		contract.setCon_emp(con_emp);
		contract.setCon_num(con_num);
		contract.setCon_type(con_type);
		contract.setCon_status(con_status);
		contract.setCon_signdate(con_signdate);
		contract.setCon_trydate(con_trydate);
		contract.setCon_tryday(con_tryday);
		contract.setCon_tryend(con_tryend);
		contract.setCon_signnum(con_signnum);
		contract.setCon_end(con_end);
		contract.setCon_enclo(con_enclo);
		contract.setCon_remaks(con_remaks);
		
		System.out.println(contract);
		int result=cMService.updateCon(contract);
		System.out.println(result);
		
		return "../Template/showContract";
	}
	
	/**
	 * 文件上传
	 * @param photo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("photo") MultipartFile photo,HttpServletRequest request,Model model){
		
		String realPath=request.getServletContext().getRealPath("/uploads");
		 System.out.println("realPath"+realPath);
			String uploadPath=realPath+"/"+photo.getOriginalFilename();
			System.out.println("uploadPath="+uploadPath);
	   String fileName=photo.getOriginalFilename();
		try {
			//转存
			IOUtils.copy(photo.getInputStream(),new FileOutputStream(new File(uploadPath)));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//model.addAttribute("fileName",photo.getOriginalFilename());
		//return "../Template/updateCon";
		Map<String, Object> map=new HashMap<>();
		map.put("fileName", fileName);
		return map;
	}
	
	/**
	 * 文件下载
	 * @param fileName
	 * @param request
	 * @param response
	 * @return
	 */
	//文件下载的两种方式	
	@RequestMapping("/down")
	public String down(String fileName,HttpServletRequest request,HttpServletResponse response){
			    System.out.println(fileName);
				response.setCharacterEncoding("utf-8");
				response.setContentType("multipart/form-data");
				
				try {
					String path=request.getSession().getServletContext().getRealPath("uploads");
					response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
					
					OutputStream os = response.getOutputStream();
				    //1.
					 os.write(FileUtils.readFileToByteArray(new File(path+"/"+ fileName)));
					//2.
					 /* InputStream inputStream = new FileInputStream(new File(path+"/"+ fileName));
					byte[] b = new byte[2048];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}*/
					//这里主要关闭
					os.close();
					//inputStream.close();
				} catch (FileNotFoundException e){
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		            //返回值要注意，要不然就出现下面这句错误！
		            //java+getOutputStream() has already been called for this response
				return null;
		}
	
	/**
	 * 导出查询数据
	 * @param emp
	 * @param type
	 * @param status
	 * @param date1
	 * @param date2
	 * @param date3
	 * @param date4
	 * @return
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response,String emp,String type,String status,String date1,String date2,String date3,String date4){
		
		
		try {
			System.out.println(emp+" "+type+" "+status);
			Contract contract=new Contract();
			contract.setCon_emp(emp);
			contract.setCon_type(type);
			contract.setCon_status(status);
			contract.setCon_signdate(date1);
			contract.setCon_trydate(date2);
			contract.setCon_tryend(date3);
			contract.setCon_end(date4);
			System.out.println(contract);
			
			Map<String, Object> map=new HashMap<>();
			List<ContrUser> contrUsers=cMService.findCon(contract);
			System.out.println(contrUsers);
			
			map.put("contrUsers", contrUsers);
			System.out.println(map);
			
			System.out.println("============准备生成 Excel报表===============");
			// 获取响应的 输出流
			OutputStream out = response.getOutputStream();
			// 设置下载的文件类型
			response.setContentType("application/vnd.ms-excel");
			// 设置Header,可以设置下载附件的文件名
			response.setHeader("Content-Disposition","attachment; filename=" + new String(("合同信息查询列表.xls").getBytes(), "ISO-8859-1"));
			// 创建一个工作簿对象
			WritableWorkbook book = Workbook.createWorkbook(out);
			// 创建 一个 或多个 工作表,指定工作簿选项卡的名称，以及 工作表的 索引位置
			WritableSheet sheet1 = book.createSheet("newfile", 0);

			// 创建一个字体对象，封装指定的字体
			WritableFont font1 = new WritableFont(WritableFont.createFont("隶书"), 20);
			font1.setColour(Colour.RED);
			// 创建一个 单元格 格式对象，封装指定格式
			WritableCellFormat wcTitle = new WritableCellFormat();
			wcTitle.setFont(font1);
			wcTitle.setAlignment(Alignment.CENTRE);
			// 向工作表中 添加单元格，单元格 内容 需要借助于 Label对象 或 Number对象进行封装
			sheet1.addCell(new Label(0, 0, "合同查询列表", wcTitle));
			sheet1.mergeCells(0, 0, 7, 0);
			sheet1.addCell(new Label(0, 1, "合同编号"));
			sheet1.addCell(new Label(1, 1, "单位员工"));
			sheet1.addCell(new Label(2, 1, "合同类型"));
			sheet1.addCell(new Label(3, 1, "合同状态"));
			sheet1.addCell(new Label(4, 1, "合同签订日期"));
			sheet1.addCell(new Label(5, 1, "合同到期日期"));
			sheet1.addCell(new Label(6, 1, "签约次数"));
			sheet1.addCell(new Label(7, 1, "发布人"));
			
			for(int i=0;i<8;i++){
				sheet1.setColumnView(i, 20);
			}
			
			for(int i=0;i<contrUsers.size();i++){
				
				ContrUser contrUser=contrUsers.get(i);
				sheet1.addCell(new Label(0, (i+2), contrUser.getCon_num()));
				sheet1.addCell(new Label(1, (i+2), contrUser.getCon_emp()));
				sheet1.addCell(new Label(2, (i+2), contrUser.getCon_type()));
				sheet1.addCell(new Label(3, (i+2), contrUser.getCon_status()));
				sheet1.addCell(new Label(4, (i+2), contrUser.getCon_signdate()));
				sheet1.addCell(new Label(5, (i+2), contrUser.getCon_end()));
				sheet1.addCell(new Number(6, (i+2), contrUser.getCon_signnum()));
				sheet1.addCell(new Label(7, (i+2), contrUser.getUname()));
				System.out.println(contrUser);
			}

			// 将工作簿对象 输出到磁盘
			book.write();
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
